package com.d3works.apps.account.db.repo;

import com.d3works.apps.account.db.PaymentVoucher;
import com.d3works.apps.account.exception.AccountExceptionMessage;
import com.d3works.apps.account.service.payment.paymentvoucher.PaymentVoucherSequenceService;
import com.d3works.apps.base.service.app.AppBaseService;
import com.d3works.exception.D3worksException;
import com.d3works.exception.db.repo.TraceBackRepository;
import com.d3works.exception.service.TraceBackService;
import com.d3works.i18n.I18n;
import com.d3works.inject.Beans;
import javax.persistence.PersistenceException;

public class PaymentVoucherManagementRepository extends PaymentVoucherRepository {

  @Override
  public PaymentVoucher copy(PaymentVoucher entity, boolean deep) {

    PaymentVoucher copy = super.copy(entity, deep);

    copy.setStatusSelect(STATUS_DRAFT);
    copy.setRef(null);
    copy.setPaymentDate(Beans.get(AppBaseService.class).getTodayDate(copy.getCompany()));
    copy.clearPayVoucherDueElementList();
    copy.clearPayVoucherElementToPayList();
    copy.setGeneratedMove(null);
    copy.setBankCardTransactionNumber(null);
    copy.clearBatchSet();
    copy.setImportId(null);
    copy.setReceiptNo(null);
    copy.setRemainingAmount(null);
    copy.setRemainingAllocatedAmount(null);
    copy.setToSaveEmailOk(false);
    copy.setDefaultEmailOk(false);
    copy.setEmail(null);

    return copy;
  }

  @Override
  public PaymentVoucher save(PaymentVoucher paymentVoucher) {
    try {

      Beans.get(PaymentVoucherSequenceService.class).setReference(paymentVoucher);

      return super.save(paymentVoucher);
    } catch (Exception e) {
      TraceBackService.traceExceptionFromSaveMethod(e);
      throw new PersistenceException(e.getMessage(), e);
    }
  }

  @Override
  public void remove(PaymentVoucher entity) {
    if (Beans.get(MoveRepository.class).findByPaymentVoucher(entity).count() > 0) {
      try {
        throw new D3worksException(
            TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
            I18n.get(AccountExceptionMessage.PAYMENT_VOUCHER_REMOVE_NOT_OK));
      } catch (D3worksException e) {
        throw new PersistenceException(e.getMessage(), e);
      }
    }
    super.remove(entity);
  }
}
